<?php
/***************************************************************************
 *                                sessions.php
 *                            -------------------
 *   begin                : Saturday, Feb 13, 2001
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   $Id: sessions.php,v 1.58.2.16 2005/10/30 15:17:14 acydburn Exp $
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

//
// Adds/updates a new session to the database for the given userid.
// Returns the new session ID on success.
//
function session_begin($user_id, $user_ip, $auto_create = 0, $enable_autologin = 0, $admin = 0)
{
	global $db, $config;
	global $SID;

	$cookiename = $config['cookie_name'];
	$cookiepath = $config['cookie_path'];
	$cookiedomain = $config['cookie_domain'];
	$cookiesecure = $config['cookie_secure'];

	$current_page = extract_current_page();
	$current_page = $current_page['page'];

	if ( isset($_COOKIE[$cookiename . '_sid']) || isset($_COOKIE[$cookiename . '_u']))
	{
		$session_id = request_var($cookiename . '_sid', '', false, true);
		$sessiondata['k'] = request_var($cookiename . '_k', '', false, true);
		$sessiondata['u'] = request_var($cookiename . '_u', 0, false, true);
		$sessionmethod = SESSION_METHOD_COOKIE;
	}
	else
	{
		$sessiondata = array();
		$session_id = request_var('sid', '');
		$sessionmethod = SESSION_METHOD_GET;
	}

	//
	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		$session_id = '';
	}

	$last_visit = 0;
	$current_time = time();
	$cookie_expire = $current_time + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);

	//
	// Are auto-logins allowed?
	// If allow_autologin is not set or is true then they are
	// (same behaviour as old 2.0.x session code)
	//
	if (isset($config['allow_autologin']) && !$config['allow_autologin'])
	{
		$enable_autologin = $sessiondata['k'] = false;
	}

	//
	// First off attempt to join with the autologin value if we have one
	// If not, just use the user_id value
	//
	$userdata = array();

	if (isset($sessiondata['k']) && $sessiondata['k'] && $sessiondata['u'] && !sizeof($userdata))
	{
		$sql = 'SELECT u.*
			FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
			WHERE u.uid = ' . (int) $sessiondata['u'] . "
			AND u.enabled = 1
			AND k.user_id = u.uid
			AND k.key_id = '" . md5($sessiondata['k']) . "'";
		$result = $db->sql_query($sql);

		$userdata = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		$enable_autologin = $login = 1;
	}
	else if (!$auto_create)
	{
		$sessiondata['k'] = '';
		$sessiondata['u'] = $user_id;

		$sql = 'SELECT *
			FROM ' . USERS_TABLE . '
			WHERE uid = ' . (int) $user_id . '
			AND enabled = 1';
		$result = $db->sql_query($sql);

		$userdata = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		$login = 1;
	}


	//
	// At this point either $userdata should be populated or
	// one of the below is true
	// * Key didn't match one in the DB
	// * User does not exist
	// * User is inactive
	//
	if (!sizeof($userdata) || !is_array($userdata) || !$userdata)
	{
		$sessiondata['k'] = '';
		$sessiondata['u'] = $user_id = ANONYMOUS;
		$enable_autologin = $login = 0;

		$sql = 'SELECT *
			FROM ' . USERS_TABLE . '
			WHERE uid = ' . (int) $user_id;
		$result = $db->sql_query($sql);

		$userdata = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);
	}


	//
	// Initial ban check against user id, IP and email address
	//
	preg_match('/(..)(..)(..)(..)/', $user_ip, $user_ip_parts);

	$sql = "SELECT ban_ip, ban_email
			FROM " . BANLIST_TABLE . "
			WHERE ban_ip = '" . $user_ip . "'";
	if ( $user_id != ANONYMOUS )
	{
		$email_part = substr($userdata['email'], strpos($userdata['email'], '@'));

		$sql .= " OR ban_email LIKE '" . $db->sql_escape($userdata['email']) . "'
			OR ban_email LIKE '" . $db->sql_escape($email_part) . "'";
	}
	$result = $db->sql_query($sql);

	if ( $ban_info = $db->sql_fetchrow($result) )
	{
		if ( $ban_info['ban_ip'] && $user_id <> ANONYMOUS ) {
			$sql = 'UPDATE ' . USERS_TABLE . ' SET enabled = 1 WHERE uid = ' . $user_id;
			$db->sql_query($sql);
		}
		if ( $ban_info['ban_ip'] || $ban_info['ban_email'] ) {
			if ( $session_id && $user_id <> ANONYMOUS ) {
				session_end($session_id, $user_id);
			}
			trigger_error('This account disabled', E_USER_ERROR);
		}
	}

	//
	// Create or update the session
	//
	/*$sql = "UPDATE " . SESSIONS_TABLE . "
		SET session_user_id = $user_id, session_start = $current_time, session_time = $current_time, session_page = '" . $db->sql_escape($current_page) . "', session_logged_in = $login, session_admin = $admin
		WHERE session_id = '" . $session_id . "'
		AND session_ip = '$user_ip'";*/
   	$sql_ip = ( $user_id == ANONYMOUS ? " AND session_ip = '$user_ip'" : '' );
   	$sql = "UPDATE " . SESSIONS_TABLE . "
      		SET session_ip = '$user_ip', session_start = $current_time, session_time = $current_time, session_page = '" . $db->sql_escape($current_page) . "', session_logged_in = $login, session_admin = $admin
      		WHERE session_id = '" . $session_id . "' $sql_ip
	 	AND session_user_id = '$user_id'";
	if ( !$db->sql_query($sql) || !$db->sql_affectedrows() )
	{
		$session_id = md5(dss_rand());

		$sql = "INSERT INTO " . SESSIONS_TABLE . "
			(session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_admin)
			VALUES ('$session_id', $user_id, $current_time, $current_time, '$user_ip', '" . $db->sql_escape($current_page) . "', $login, $admin)";
		$db->sql_query($sql);
	}

	if ( $user_id != ANONYMOUS )
	{
		$userdata['user_lastvisit'] = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time;

		if (!$admin)
		{
			$sql = 'UPDATE ' . USERS_TABLE . '
				SET user_session_time = ' . $current_time . ', user_session_page = \'' . $db->sql_escape($current_page) . '\', user_lastvisit = ' . $userdata['user_lastvisit'] . '
				WHERE uid = ' . $user_id;
			$db->sql_query($sql);
		}

		//
		// Regenerate the auto-login key
		//
		if ($enable_autologin)
		{
			$auto_login_key = dss_rand() . dss_rand();

			if (isset($sessiondata['k']) && (string) $sessiondata['k'] != '')
			{
				$sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
					SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
					WHERE key_id = '" . md5($sessiondata['k']) . "'";
			}
			else
			{
				$sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . "(key_id, user_id, last_ip, last_login)
					VALUES ('" . md5($auto_login_key) . "', $user_id, '$user_ip', $current_time)";
			}

			$db->sql_query($sql);

			$sessiondata['k'] = $auto_login_key;
			unset($auto_login_key);
		}
		else
		{
			$sessiondata['k'] = '';
		}
		$sessiondata['u'] = $user_id;

		set_cookie('k', $sessiondata['k'], $cookie_expire);
		set_cookie('u', $sessiondata['u'], $cookie_expire);
		set_cookie('sid', $session_id, $cookie_expire);
	}

	$userdata['session_id'] = $session_id;
	$userdata['session_ip'] = $user_ip;
	$userdata['session_user_id'] = $user_id;
	$userdata['session_logged_in'] = $login;
	$userdata['session_page'] = $current_page;
	$userdata['session_start'] = $current_time;
	$userdata['session_time'] = $current_time;
	$userdata['session_admin'] = $admin;
	$userdata['session_key'] = $sessiondata['k'];

	//$SID = 'sid=' . $session_id;
	$SID = ( $user_id <> ANONYMOUS ? $session_id : '' );

	return $userdata;
}

//
// Checks for a given user session, tidies session table and updates user
// sessions at each page refresh
//
function session_pagestart($user_ip)
{
	global $db, $lang, $config;
	global $SID;

	$cookiename = $config['cookie_name'];
	$cookiepath = $config['cookie_path'];
	$cookiedomain = $config['cookie_domain'];
	$cookiesecure = $config['cookie_secure'];

	$current_page = extract_current_page();
	$current_page = $current_page['page'];

	$current_time = time();
	$cookie_expire = $current_time + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);
	unset($userdata);

	if ( isset($_COOKIE[$cookiename . '_sid']) || isset($_COOKIE[$cookiename . '_u']) )
	{
		$session_id = request_var($cookiename . '_sid', '', false, true);
		$sessiondata['k'] = request_var($cookiename . '_k', '', false, true);
		$sessiondata['u'] = request_var($cookiename . '_u', '', false, true);
		$sessionmethod = SESSION_METHOD_COOKIE;
	}
	else
	{
		$sessiondata = array();
		$session_id = request_var('sid', '');
		$sessionmethod = SESSION_METHOD_GET;
	}

	//
	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		$session_id = '';
	}

	//
	// Does a session exist?
	//
	if ( !empty($session_id) )
	{
		//
		// session_id exists so go ahead and attempt to grab all
		// data in preparation
		//
		$sql = 'SELECT u.*, s.*
			FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . ' u
			WHERE s.session_id = \'' . $session_id . '\'
			AND u.uid = s.session_user_id';
		$result = $db->sql_query($sql);

		$userdata = $db->sql_fetchrow($result);

		//
		// Did the session exist in the DB?
		//
		if ( isset($userdata['uid']) )
		{
			//
			// Do not check IP assuming equivalence, if IPv4 we'll check only first 24
			// bits ... I've been told (by vHiker) this should alleviate problems with
			// load balanced et al proxies while retaining some reliance on IP security.
			//
			$ip_check_s = substr($userdata['session_ip'], 0, 6);
			$ip_check_u = substr($user_ip, 0, 6);

			if ($ip_check_s == $ip_check_u)
			{
				//$SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';
				$SID = ( $userdata['uid'] <> ANONYMOUS ? (($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? $session_id : '') : '' );

				//
				// Only update session DB a 1 minute or so after last update
				//
				if ( $current_time - $userdata['session_time'] > 5 * 60 )
				{
					// A little trick to reset session_admin on session re-usage
					$update_admin = (!defined('IN_ADMIN') && $current_time - $userdata['session_time'] > ($config['session_length'] + 60 )) ? ', session_admin = 0' : '';
					//$update_forum_sql = ( defined('IN_PHPBB') || ( strpos($current_page, 'phpbb2.php') === true ) ? ', user_lastvisit = ' . $current_time : '' );

					$sql = 'UPDATE ' . SESSIONS_TABLE . '
						SET session_time = ' . $current_time . ', session_page = \'' . $db->sql_escape($current_page) . '\'' . $update_admin . '
						WHERE session_id = \'' . $userdata['session_id'] . '\'';
					$db->sql_query($sql);
					if ( $userdata['uid'] != ANONYMOUS )
					{
						$sql = 'UPDATE ' . USERS_TABLE . '
							SET user_session_time =  ' . $current_time . ', user_session_page = \'' . $db->sql_escape($current_page) . '\', ip = \'' . $user_ip . '\'
							WHERE uid = ' . $userdata['uid'];
						$db->sql_query($sql);
					}

					//set_cookie('k', $sessiondata['k'], $cookie_expire);
					//set_cookie('u', $sessiondata['u'], $cookie_expire);
					//set_cookie('sid', $session_id, $cookie_expire);
				}

				// Add the session_key to the userdata array if it is set
				if ( isset($sessiondata['k']) && $sessiondata['k'] != '' )
				{
					$userdata['session_key'] = $sessiondata['k'];
				}

				return $userdata;
			}
		}
	}

  	/*else
   	{
   		 // try to login guest
		$sql = 'SELECT u.*, s.*
			FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . ' u
			WHERE s.session_ip = \'' . $user_ip . '\'
			AND s.session_user_id = ' . ANONYMOUS . '
			AND u.uid = s.session_user_id
			LIMIT 0, 1';
		$result = $db->sql_query($sql);

      	$userdata = $db->sql_fetchrow($result);

    		if ( isset($userdata['uid']) )
    		{
    			$sql = 'UPDATE ' . SESSIONS_TABLE . '
    				SET session_time = ' . $current_time . ', session_start = ' . $current_time . ', session_page = \'' . $db->sql_escape($current_page) . '\'
    				WHERE session_id = \'' . $userdata['session_id'] . '\'';

    			$db->sql_query($sql);

	   		return $userdata;
	   	}
	}*/

	//
	// If we reach here then no (valid) session exists. So we'll create a new one,
	// using the cookie user_id if available to pull basic user prefs.
	//
	$user_id = ( isset($sessiondata['u']) ) ? (int) $sessiondata['u'] : ANONYMOUS;

	if ( !($userdata = session_begin($user_id, $user_ip, TRUE)) )
	{
		trigger_error('Error creating user session');
	}
	return $userdata;

}

/**
* Terminates the specified session
* It will delete the entry in the sessions table for this session,
* remove the corresponding auto-login key and reset the cookies
*/
function session_end($session_id, $user_id)
{
	global $db, $lang, $config, $userdata;
	global $_COOKIE, $_GET, $SID;

	$cookiename = $config['cookie_name'];
	$cookiepath = $config['cookie_path'];
	$cookiedomain = $config['cookie_domain'];
	$cookiesecure = $config['cookie_secure'];

	$autologinkey = request_var($cookiename . '_k', '', false, true);

	$current_time = time();
	$cookie_expire = $current_time - 31536000;

	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		return;
	}

	//
	// Delete existing session
	//
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . '
		WHERE session_id = \'' . $session_id . '\'
		AND session_user_id = ' . $user_id;
	$db->sql_query($sql);

	//
	// Remove this auto-login entry (if applicable)
	//
	if ( $autologinkey != '' )
	{
		$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
			WHERE user_id = ' . (int) $user_id . '
			AND key_id = \'' . md5($autologinkey) . '\'';
		$db->sql_query($sql);
	}

	//
	// We expect that message_die will be called after this function,
	// but just in case it isn't, reset $userdata to the details for a guest
	//
	$sql = 'SELECT *
		FROM ' . USERS_TABLE . '
		WHERE uid = ' . ANONYMOUS;
	$result = $db->sql_query($sql);
	$userdata = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

	set_cookie('sid', '', $cookie_expire);
	set_cookie('u', '', $cookie_expire);
	set_cookie('k', '', $cookie_expire);

	return true;
}

/**
* Reset all login keys for the specified user
* Called on password changes
*/
function session_reset_keys($user_id, $user_ip)
{
	global $db, $userdata, $config;

	$key_sql = ($user_id == $userdata['uid'] && !empty($userdata['session_key'])) ? "AND key_id != '" . md5($userdata['session_key']) . "'" : '';

	$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
		WHERE user_id = ' . (int) $user_id . "
			$key_sql";

	$db->sql_query($sql);

	$where_sql = 'session_user_id = ' . (int) $user_id;
	$where_sql .= ($user_id == $userdata['uid']) ? " AND session_id <> '" . $userdata['session_id'] . "'" : '';
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . "
		WHERE $where_sql";
	$db->sql_query($sql);

	if ( !empty($key_sql) )
	{
		$auto_login_key = dss_rand() . dss_rand();

		$current_time = time();
		$cookie_expire = $current_time + 31536000;

		$sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
			SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
			WHERE key_id = '" . md5($userdata['session_key']) . "'";

		$db->sql_query($sql);

		// And now rebuild the cookie
		$sessiondata['u'] = $user_id;
		$sessiondata['k'] = $auto_login_key;
		$cookiename = $config['cookie_name'];
		$cookiepath = $config['cookie_path'];
		$cookiedomain = $config['cookie_domain'];
		$cookiesecure = $config['cookie_secure'];

		set_cookie('k', $sessiondata['k'], $cookie_expire);
		set_cookie('u', $sessiondata['u'], $cookie_expire);

		$userdata['session_key'] = $auto_login_key;
		unset($sessiondata);
		unset($auto_login_key);
	}
}

function set_cookie($name, $cookiedata, $cookietime = 0 )
{
	global $config;

	$name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata);
	$expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
	$domain = (!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain'];

	header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . '; HttpOnly', false);
}

//
// Initialise user settings on page load
function init_userprefs($userdata)
{
	global $config, $theme, $images;
	global $template, $lang, $phpEx, $tracker_root_path, $db;

	if ( $userdata['uid'] != ANONYMOUS )
	{
		if ( !empty($userdata['language']))
		{
			$default_lang = $userdata['language'];
		}

		if ( isset($userdata['tzoffset']) )
		{
			$config['board_timezone'] = number_format($userdata['tzoffset']);
		}
	}

	else
	{
		$default_lang = $config['default_lang'];
		$dir = opendir($tracker_root_path . 'languages');
		$lang_files = array();
		while ( $file = readdir($dir) ) {
			if (preg_match('#^lang_#i', $file) && !is_file($dir . '/' . $file) && !is_link($dir . '/' . $file)) {
				$filename = trim(str_replace("lang_", "", $file));
				$filename = strtolower($filename);
				$lang_files[format_language($filename)] = $filename;
			}
		}

		if ( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) {
			$accept_lang_ary = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
			foreach ($accept_lang_ary AS $accept_lang) {
				$accept_lang_short = substr($accept_lang, 0, 2);
				if ( array_key_exists($accept_lang_short, $lang_files) ) {
					$default_lang = $lang_files[$accept_lang_short];
					break;
				}
				else {
					$accept_lang_short = substr($accept_lang, 3, 2);
					if ( $accept_lang_short ) {
						if ( array_key_exists($accept_lang_short, $lang_files) ) {
							$default_lang = $lang_files[$accept_lang_short];
							break;
 		       				}
					}
				}
			}
		}
	}

	if ( !@file_exists($tracker_root_path . 'languages/lang_' . $default_lang . '/lang_main.php') )
	{
		if ( $userdata['uid'] != ANONYMOUS )
		{
			// For logged in users, try the board default language next
			$default_lang = $config['default_lang'];
		}
		else
		{
			// For guests it means the default language is not present, try english
			// This is a long shot since it means serious errors in the setup to reach here,
			// but english is part of a new install so it's worth us trying
			$default_lang = 'english';
		}

		if ( !@file_exists($tracker_root_path . 'languages/lang_' . $default_lang . '/lang_main.php') )
		{
			trigger_error("Could not locate valid language pack");
		}
	}

	// If we've had to change the value in any way then let's write it back to the database
	// before we go any further since it means there is something wrong with it
	if ( $userdata['uid'] != ANONYMOUS && $userdata['language'] !== $default_lang )
	{
		$sql = 'UPDATE ' . USERS_TABLE . " SET language = '" . $default_lang . "' WHERE language = '" . $db->sql_escape($userdata['language']) . "'";

		$db->sql_query($sql);

		$userdata['language'] = $default_lang;
	}
	elseif ( $userdata['uid'] === ANONYMOUS && $config['default_lang'] !== $default_lang )
	{
		set_config('default_lang', $default_lang);
	}

	//$config['default_lang'] = $default_lang;

	include($tracker_root_path . 'languages/lang_' . $default_lang . '/lang_main.php');

	if ( defined('IN_PHPBB') )
	{
		include($tracker_root_path . 'languages/lang_' . $default_lang . '/lang_forum.php');
	}

	if ( defined('IN_ADMIN') )
	{
		include($tracker_root_path . 'languages/lang_' . $default_lang . '/lang_admin.php');
	}

	if ( !empty($config['default_language_charset']) && strtolower($lang['language_charset']) != strtolower($config['default_language_charset']) ) {
			charset_encoder($lang['language_charset'], $config['default_language_charset'], $lang);
	}

	//
	// Set up style
	//
	if ( !$config['override_user_style'] )
	{
		if ( $userdata['uid'] != ANONYMOUS && $userdata['user_style'] > 0 )
		{
			if ( $theme = setup_style($userdata['user_style']) )
			{
				return;
			}
		}
	}

	$theme = setup_style($config['default_style']);

	return;
}

function setup_style($style) {
	global $db, $config, $template, $tracker_root_path, $lang, $images, $template_path, $userdata;

	require_once ($tracker_root_path . 'include/class.template.php');

	$sql = 'SELECT * FROM ' . THEMES_TABLE . ' WHERE themes_id = ' . $style;
     $result = $db->sql_query($sql, 31536000);
     if ( !($row = $db->sql_fetchrow($result)) ) {
		$db->sql_freeresult($result);

		if ( $style != $config['default_style'] ) {
			$sql = 'SELECT * FROM ' . THEMES_TABLE . ' WHERE themes_id = ' . $config['default_style'];
			$result = $db->sql_query($sql, 31536000);

			if ( $row = $db->sql_fetchrow($result) ) {
				$db->sql_freeresult($result);
				$sql = 'UPDATE ' . USERS_TABLE . '
						SET user_style = ' . $config['default_style'] . '
						WHERE user_style = ' . $style;
				$db->sql_query($sql);
		     }
			else {
				trigger_error("Could not get theme data for themes_id [$style]", E_USER_ERROR);
		     }
		}
		else {
			trigger_error("Could not get theme data for themes_id [$style]", E_USER_ERROR);
		}
		return;
	}
	$db->sql_freeresult($result);
     $template_name = $row['style_name'];

     $template = new template;
     $template_path = $tracker_root_path . 'templates/' . $row['template_name'];
     $template->set_template($row['template_name']);

	if ( $template ) {
		$images = array();
		$current_template_images = $tracker_root_path . 'templates/' . $row['template_name'];
		@include($template_path . '/' . $row['template_name'] . '.cfg');

		if ( !defined('TEMPLATE_CONFIG') ) {
			trigger_error("Could not open $template_name template config file");
		}

		$img_lang = ( file_exists($template_path . '/images/lang_' . $userdata['language']) ) ? $userdata['language'] : $config['default_lang'];
		foreach ( $images AS $key => $value ) {
			if ( !is_array($value) ) {
				$images[$key] = str_replace('{LANG}', 'lang_' . $img_lang, $value);
		     }
		}
		$userdata['template_path'] = $template_path;
	//	$userdata['theme_bitfield'] = $row['bbcode_bitfield'];

		$template->assign_vars(array(
			'TEMPLATE_PATH' => $template_path
		));
	}
	else {
		trigger_error("Could not initialize template [$style]");
     }
     return $row;
}

/**
* Our own generator of random values
* This uses a constantly changing value as the base for generating the values
* The board wide setting is updated once per page if this code is called
* With thanks to Anthrax101 for the inspiration on this one
* Added in phpBB 2.0.20
*/
function dss_rand()
{
	global $config, $dss_seeded;

	$val = $config['rand_seed'] . microtime();
	$val = md5($val);
	$config['rand_seed'] = md5($config['rand_seed'] . $val . 'a');

	if($dss_seeded !== true)
	{
		set_config('rand_seed', $config['rand_seed'], true);

		$dss_seeded = true;
	}

	return substr($val, 4, 16);
}

/**
* Extract current session page
*
* @param string $root_path current root path ($tracker_root_path)
* copyright by phpBB
*/

function extract_current_page()
{
	global $tracker_root_path;

	$page_array = array();

	// First of all, get the request uri...
	$script_name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
	$args = (!empty($_SERVER['QUERY_STRING'])) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));

	// If we are unable to get the script name we use REQUEST_URI as a failover and note it within the page array for easier support...
	if (!$script_name)
	{
		$script_name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
		$script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
		$page_array['failover'] = 1;
	}

	// Replace backslashes and doubled slashes (could happen on some proxy setups)
	$script_name = str_replace(array('\\', '//'), '/', $script_name);

	// Now, remove the sid and let us get a clean query string...
	$use_args = array();

	// Since some browser do not encode correctly we need to do this with some "special" characters...
	// " -> %22, ' => %27, < -> %3C, > -> %3E
	$find = array('"', "'", '<', '>');
	$replace = array('%22', '%27', '%3C', '%3E');

	foreach ($args as $key => $argument)
	{
		if (strpos($argument, 'sid=') === 0 || strpos($argument, '_f_=') === 0)
		{
			continue;
		}

		$use_args[str_replace($find, $replace, $key)] = str_replace($find, $replace, $argument);
	}
	unset($args);

	// The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2

	// The current query string
	$query_string = trim(implode('&', $use_args));

	// basenamed page name (for example: index.php)
	$page_name = basename($script_name);
	$page_name = urlencode(htmlspecialchars($page_name));

	// current directory within the phpBB root (for example: adm)
	$root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($tracker_root_path)));
	$page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
	$intersection = array_intersect_assoc($root_dirs, $page_dirs);

	$root_dirs = array_diff_assoc($root_dirs, $intersection);
	$page_dirs = array_diff_assoc($page_dirs, $intersection);

	$page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);

	if ($page_dir && substr($page_dir, -1, 1) == '/')
	{
		$page_dir = substr($page_dir, 0, -1);
	}

	// Current page from phpBB root (for example: adm/index.php?i=10&b=2)
	$page = (($page_dir) ? $page_dir . '/' : '') . $page_name . (($query_string) ? "?$query_string" : '');

	// The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in /
	$script_path = trim(str_replace('\\', '/', dirname($script_name)));

	// The script path from the webroot to the phpBB root (for example: /phpBB3/)
	$script_dirs = explode('/', $script_path);
	array_splice($script_dirs, -sizeof($page_dirs));
	$root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');

	// We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
	if (!$root_script_path)
	{
		$root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
	}

	$script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
	$root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';

	$page_array += array(
		'page_name'			=> $page_name,
		'page_dir'			=> $page_dir,

		'query_string'		=> $query_string,
		'script_path'		=> str_replace(' ', '%20', htmlspecialchars($script_path)),
		'root_script_path'	=> str_replace(' ', '%20', htmlspecialchars($root_script_path)),

		'page'				=> $page
	);

	return $page_array;
}

function _checkdnsrr($host, $type = '')
{
	$type = (!$type) ? 'MX' : $type;

	if (strpos(PHP_OS, 'WIN') !== false)
	{
		if (!function_exists('exec'))
		{
			return NULL;
		}

		@exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host), $output);

		// If output is empty, the nslookup failed
		if (empty($output))
		{
			return NULL;
		}

		foreach ($output as $line)
		{
			if (!trim($line))
			{
				continue;
			}

			// Valid records begin with host name:
			if (strpos($line, $host) === 0)
			{
				return true;
			}
		}

		return false;
	}
	else if (function_exists('checkdnsrr'))
	{
		return (checkdnsrr($host, $type)) ? true : false;
	}

	return NULL;
}

function check_dnsbl($mode, $ip = false)
{
	global $user_ip;

	if ($ip === false)
	{
		$ip = $user_ip;
	}

	$dnsbl_check = array(
		'list.dsbl.org'			=> 'http://dsbl.org/listing?',
		'sbl-xbl.spamhaus.org'		=> 'http://www.spamhaus.org/query/bl?ip=',
	);

	if ($mode == 'register')
	{
		$dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?';
	}

	if ($ip)
	{
		$quads = explode('.', $ip);
		$reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];

		// Need to be listed on all servers...
		$listed = true;
		$info = array();

		foreach ($dnsbl_check as $dnsbl => $lookup)
		{
			if (_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true)
			{
				$info = array($dnsbl, $lookup . $ip);
			}
			else
			{
				$listed = false;
			}
		}

		if ($listed)
		{
			return $info;
		}
	}

	return false;
}

function charset_encoder ($from, $to, &$array) {
	if ( function_exists('iconv') ) {
		foreach ( $array AS $a => $b ) {
			if ( is_array($b) ) {
				charset_encoder ($from, $to, $b);
				$array[$a] = $b;
			}
			else {
				$array[$a] = iconv($from, $to, $b);
			}
		}
	}
	else {
		return $array;
	}
}


/**
* Append session id to url.
*
* @param string $url The url the session id needs to be appended to (can have params)
* @param mixed $params String or array of additional url parameters
* @param bool $is_amp Is url using &amp; (true) or & (false)
* @param string $session_id Possibility to use a custom session id instead of the global one
*
* Examples:
* <code>
* append_sid("{$tracker_root_path}viewtopic.$phpEx?t=1&amp;f=2");
* append_sid("{$tracker_root_path}viewtopic.$phpEx", 't=1&amp;f=2');
* append_sid("{$tracker_root_path}viewtopic.$phpEx", 't=1&f=2', false);
* append_sid("{$tracker_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
* </code>
*
*/
function append_sid($url, $params = false, $is_amp = true, $session_id = false)
{
	global $SID, $_EXTRA_URL;

	// Assign sid if session id is not specified
	if ($session_id === false)
	{
		$session_id = $SID;
	}

	$amp_delim = ($is_amp) ? '&amp;' : '&';
	$url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;

	// Appending custom url parameter?
	$append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';

	$anchor = '';
	if (strpos($url, '#') !== false)
	{
		list($url, $anchor) = explode('#', $url, 2);
		$anchor = '#' . $anchor;
	}
	else if (!is_array($params) && strpos($params, '#') !== false)
	{
		list($params, $anchor) = explode('#', $params, 2);
		$anchor = '#' . $anchor;
	}
	// Use the short variant if possible ;)
	if ($params === false)
	{
		// Append session id
		if (!$session_id)
		{
			return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
		}
		else
		{
			return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
		}
	}

	// Build string if parameters are specified as array
	if (is_array($params))
	{
		$output = array();

		foreach ($params as $key => $item)
		{
			if ($item === NULL)
			{
				continue;
			}

			if ($key == '#')
			{
				$anchor = '#' . $item;
				continue;
			}

			$output[] = $key . '=' . $item;
		}

		$params = implode($amp_delim, $output);
	}

	// Append session id and parameters (even if they are empty)
	// If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
	return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
}

?>